% Define number of bits per symbol (k).
M = 4;  % or 2
k = log2(M);

% number of bits per iteration
bitsPerIter = 1e1;

% Code properties
 codeRate = 1/2;
 constlen = 7;
 codegen = [171 133];
 tblen = 32;     % traceback length
 trellis = poly2trellis(constlen, codegen);

for EbNo = 0.01;
% 
%     % Create Gray encoding and decoding array
     grayCode = bitxor(0:M-1, floor((0:M-1)/2));
% 
%     % Initialize the leftover vector with all zeros to create a decoder
%     % 'prehistory' of 0's.
%     msg_orig_lo = zeros(tblen, 1);

    % Reset the encoder/decoder states and persistent data
    stateEnc = [];
    metric = [];
    stateDec = [];
    in = [];

    % Initialize the bit error rate and error counters.
    totErr = 0;
    numBits = 0;
    initCompIdx = 1;
    iter = 1;

    % Generate binary random numbers
    msg_orig = randint(bitsPerIter, 1);
    

    % Convolutionally encode the message, saving encoder state between iterations
    [msg_enc_bi, stateEnc] = convenc(msg_orig, trellis, stateEnc);

    

    % Change binary symbols to quaternary symbols, and gray encode to ensure
    % one bit transition per symbol
     msg_enc = bi2de(reshape(msg_enc_bi, k, length(msg_enc_bi) / k)');
     msg_gr_enc = grayCode(msg_enc+1);
     msg_tx1 = de2bi(msg_gr_enc,2,'left-msb');
     [rows, columns] = size(msg_tx1);
        for i=1:rows
                   for j=1:columns
                       msg_tx2(1,(i-1)*columns+j)= msg_tx1(i,j);
                   end
        end

    % Digitally modulate the signal.
    % msg_tx = modulate(modem.pskmod(M), msg_gr_enc);
     msg_tx = ook_mod(msg_tx2,10);

    % Adjust SNR for coded bits and multi-bit symbols.
     adjSNR = EbNo - 10*log10(1/codeRate) + 10*log10(k);

     % Add Gaussian noise to the signal.
     msg_txf=apply_lognormal(0.01,msg_tx);
    
     msg_rx = awgn(msg_txf, adjSNR, 'measured', [], 'dB');
   
    % Demodulate and detect the signal
    % msg_gr_demod = demodulate(modem.pskdemod(M), msg_rx);
     msg_gr_demod = ook_demod(msg_rx,10);
     len = length(msg_gr_demod);
        for i = 0:(len/2)-1
            b2c(i+1) = bi2de(msg_gr_demod(i*2+1:(i*2)+2),'left-msb');
        end  
         
    % Gray decode and change demodulated symbols to bits
      msg_demod = grayCode(b2c+1)  ;
      msg_demod_bi = de2bi(msg_demod, k)';

    % Use the Viterbi algorithm to decode the received signal.  Save the
    % trellis and metric states from iteration to iteration in
    % 'metric', 'stateDec', and 'in'.
     [msg_dec, metric, stateDec, in] = vitdec(msg_demod_bi(:), trellis, ...
      tblen, 'cont', 'hard', metric, stateDec, in);


    [a,b] = biterr(msg_dec, msg_orig)
end
